<template>
  <view class="add-house-info">
    <view class="house-title">
      <view class="title">
        房屋信息
      </view>
      <view class="content">
        <text>{{title}}</text>
        <view class="right" v-if="id">
          <view class="success" v-if="status === 2">
            审核通过
          </view>
          <view class="waiting" v-if="status === 1">
            审核中
          </view>
          <view class="error" v-if="status === 3">
            审核失败
          </view>
        </view>
      </view>
    </view>
    <view class="house-content">
      <view class="title">
        业主信息
      </view>
      <view class="content">
        <u--form ref="form" :model="form" :rules="rules">
          <u-form-item label="姓名" borderBottom labelWidth="208rpx" prop="name" ref="item1">
            <u--input v-model="form.name" placeholder="请输入你的真实姓名" border="none"></u--input>
          </u-form-item>
          <u-form-item label="性别" borderBottom labelWidth="208rpx" prop="gender">
            <u-radio-group v-model="form.gender">
              <u-radio activeColor="#5591AF" :customStyle="{marginRight: '60rpx'}" v-for="(item, index) in gender"
                :key="index" :label="item.name" :name="item.name === '男'?1:0">
              </u-radio>
            </u-radio-group>
          </u-form-item>
          <u-form-item label="手机号" borderBottom labelWidth="208rpx" prop="mobile">
            <view slot="right" class="code">
              <u-count-down @finish="onFinish" v-if="isShowCountDown" :time="6 * 1000" format="ss s后可重新发送">
              </u-count-down>
              <view v-else @click="getCode" class="code-btn">获取验证码</view>
            </view>
            <u--input v-model="form.mobile" placeholder="请输入您的手机号" border="none"></u--input>
          </u-form-item>
          <u-form-item label="验证码" borderBottom labelWidth="208rpx" prop="code">
            <u--input v-model="form.code" placeholder="请输入手机验证码" border="none"></u--input>
          </u-form-item>
        </u--form>
      </view>
    </view>
    <view class="house-bottom">
      <u-cell-group :border="false">
        <u-cell title="上传本人身份证照片">
          <view class="label" slot="label">
            请拍摄证件原件，并使照片中证件边缘完整，文字清晰，光线均匀。
          </view>
        </u-cell>
      </u-cell-group>
      <view class="uploadBoxs" v-if="isShowUploadBoxs">
        <u-upload :maxCount="1" :fileList="fileList1" name="1" @afterRead="afterRead" width="690rpx" height="340rpx"
          uploadIcon="plus" uploadText="上传人像面照片" uploadIconColor="#7694B0" @delete="deletePic">
        </u-upload>
        <u-upload :maxCount="1" :fileList="fileList2" name="2" @afterRead="afterRead" @delete="deletePic" width="690rpx"
          height="340rpx" uploadIcon="plus" uploadText="上传国徽面照片" uploadIconColor="#7694B0">
        </u-upload>
      </view>
      <life-button @click="onCheck" :icon="buttonIcon" :title="id?'修改报修房屋':'提交审核'"></life-button>
    </view>
    <!-- 模拟短信提示 -->
    <u-notify @click.native="copyCode" ref="uNotify"></u-notify>
  </view>
</template>

<script>
  import {
    addHouse,
    updateStatus,
    getHouseDetail
  } from '../../api/house.js'
  import {
    sendCode
  } from '../../api/login.js'
  export default {
    data() {
      return {
        isShowUploadBoxs: false,
        id: null,
        status: null,
        buttonIcon: '../../static/icon/check.png',
        fileList1: [],
        fileList2: [],
        code: '',
        isShowCountDown: false,
        title: '',
        form: {
          name: '张三',
          gender: 1,
          mobile: '18900000000',
          code: ''
        },
        rules: {
          name: [{
              required: true,
              message: '请填写姓名',
              trigger: ['blur', 'change']
            },
            {
              pattern: /^(?:[\u4e00-\u9fa5·]{2,4})$/,
              message: '请填写正确的名字',
              trigger: ['blur', 'change']
            }
          ],
          mobile: [{
              required: true,
              message: '请输入手机号',
              trigger: ['change', 'blur'],
            },
            {
              pattern: /^((\+|00)86)?1((3[\d])|(4[5,6,7,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[\d])|(9[1,8,9]))\d{8}$/,
              message: '手机号码格式不正确',
              trigger: ['change', 'blur'],
            }
          ],
          code: [{
            required: true,
            message: '请输入验证码',
            trigger: ['change', 'blur'],
          }, {
            pattern: /^\d{6}$/,
            message: '验证码格式不正确',
            trigger: ['change', 'blur'],
          }]
        },
        gender: [{
            name: '男',
            disabled: true
          },
          {
            name: '女',
            disabled: false
          }
        ]
      }
    },
    methods: {
      // 显示房屋信息
      async getHouseDetail(id) {
        // 请求房屋信息
        const {
          data
        } = await getHouseDetail(id)
        // 渲染数据
        this.title = data.point + ' ' + data.building + ' ' + data.room
        this.form.name = data.name
        this.form.gender = data.gender
        this.form.id = data.id
        this.form.mobile = data.mobile
        this.status = data.status
        this.afterRead({
          name: '1',
          index: 0,
          file: {
            type: "image",
            url: data.idcardBackUrl,
            thumb: data.idcardBackUrl
          }
        })
        this.afterRead({
          name: '2',
          index: 0,
          file: {
            type: "image",
            thumb: data.idcardFrontUrl,
            url: data.idcardFrontUrl
          }
        })
      },
      async onCheck() {
        try {
          // 表单校验
          await this.$refs.form.validate()
          // 上传身份证校验
          if (!this.fileList1.length || !this.fileList2.length) {
            uni.showToast({
              title: '请上传身份证',
              icon: 'none',
              duration: 2000
            })
          }
          const arr = this.title.split(' ')
          // 删除code属性
          delete this.form.code
          // 发送添加房屋请求
          const res = await addHouse({
            point: arr[0],
            building: arr[1],
            room: arr[2],
            ...this.form
          })
          console.log(res);
          const res1 = await updateStatus({
            type: 'room',
            status: '2',
            id: res.data.id
          })
          uni.showToast({
            title: '添加房屋成功',
            icon: 'success'
          })
          uni.navigateTo({
            url: '/pkg-house/house/house'
          })
        } catch (err) {
          //TODO handle the exception
          console.log(err);
        }
      },
      // 删除图片
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1)
      },
      async afterRead(e) {
        let lists = [].concat(e.file)
        let fileListLen = this[`fileList${e.name}`].length
        lists.map((item) => {
          this[`fileList${e.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url, e.name)
          let item = this[`fileList${e.name}`][fileListLen]
          this[`fileList${e.name}`].splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: result
          }))
          fileListLen++
        }
        // 显示上传图片组件
        this.isShowUploadBoxs = true
      },
      // 上传回调
      FilePromise(locationUrl, header, num) {
        console.log('开始上传');
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: 'https://live-api.itheima.net/upload', // 仅为示例，非真实的接口地址
            filePath: locationUrl,
            header: header,
            name: 'file',
            formData: {
              file: locationUrl
            },
            success: (res) => {
              const res1 = JSON.parse(res.data)
              console.log('上传成功');
              resolve(res1.data)
              if (num === '1') {
                this.form.idcardBackUrl = res1.data.url
              } else {
                this.form.idcardFrontUrl = res1.data.url
              }
            }
          });
        })
      },
      // 上传图片
      async uploadFilePromise(url, num) {
        const token = this.$store.state.user.userToken.token
        const header = {
          Authorization: 'Bearer ' + token
        }
        if (this.id) {
          let locationUrl = url
          await uni.downloadFile({
            url: locationUrl,
            success: (res2) => {
              if (res2.statusCode === 200) {
                console.log('下载成功');
                locationUrl = res2.tempFilePath
                return this.FilePromise(locationUrl, header, num)
              }
            }
          })
        } else {
          return this.FilePromise(url, header, num)
        }
      },
      // 倒计时结束
      onFinish() {
        this.isShowCountDown = false
      },
      // 复制
      copyCode() {
        uni.setClipboardData({
          data: this.code
        })
      },
      // 发送验证码
      getCode() {
        // 校验手机号
        this.$refs.form.validateField('mobile', async (errRes) => {
          if (errRes.length) return
          // 手机号合法，发请求
          const res = await sendCode(this.form.mobile)
          // message
          const message = `【享+生活】验证码：${res.data.code}.您正在使用短信验证码功能，验证码提供他人可能导致账号被盗，请勿转发或泄漏。`
          this.code = res.data.code
          // 短信提示
          this.$refs.uNotify.show({
            top: 10,
            type: 'success',
            message: message,
            duration: 1000 * 6,
            fontSize: 14
          })
          // 震动
          uni.vibrateLong()
          // 显示倒计时
          this.isShowCountDown = true
        })
      },
    },
    onLoad(options) {
      if (options.id) {
        this.id = options.id
        this.getHouseDetail(options.id)
        this.buttonIcon = '../../static/icon/revise.png'
        uni.setNavigationBarTitle({
          title: '房屋信息'
        })
      } else {
        this.title = options.title
        this.isShowUploadBoxs = true
      }
    },
    // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
    onReady() {
      this.$refs.form.setRules(this.rules);
    }
  }
</script>

<style lang="scss" scoped>
  .add-house-info {
    height: 100%;
    background-color: #FAFAFA;
    padding-bottom: 670rpx;

    .house-title {
      .title {
        padding: 30rpx;
        color: #979797;
        font-size: 24rpx;

      }

      .content {
        padding: 30rpx;
        color: #333333;
        font-size: 28rpx;
        line-height: 1.5;
        letter-spacing: 0rpx;
        background-color: #fff;
        display: flex;
        justify-content: space-between;

        .right {
          .success {
            width: 128rpx;
            height: 48rpx;
            color: #27AE60;
            border-radius: 10rpx;
            background: #EBF8F0;
            font-size: 24rpx;
            line-height: 48rpx;
            text-align: center;
          }

          .waiting {
            width: 104rpx;
            height: 48rpx;
            border-radius: 10rpx;
            background: #E5F0FB;
            text-align: center;
            line-height: 48rpx;
            font-size: 24rpx;
            color: #2D9CDB;
          }

          .error {
            width: 128rpx;
            height: 48rpx;
            color: #EB5757;
            border-radius: 10rpx;
            background: #FCF2ED;
            font-size: 24rpx;
            line-height: 48rpx;
            text-align: center;
          }
        }
      }
    }

    .house-content {
      .title {
        padding: 30rpx;
        color: #979797;
        font-size: 24rpx;

      }

      .content {
        background-color: #fff;

        padding: 0 0 0 30rpx;

        ::v-deep .u-form-item__body {
          padding: 30rpx 30rpx 30rpx 0;
        }

        .code {
          color: #5591AF;
          font-size: 28rpx;

        }
      }
    }

    .house-bottom {
      background-color: #fff;
      margin: 30rpx 0 62rpx;
      padding: 30rpx 0 30rpx 30rpx;
      box-sizing: border-box;
      overflow: hidden;

      ::v-deep .u-cell__body {
        padding: 0;
      }

      ::v-deep .u-cell__body {
        padding-bottom: 21rpx;
      }

      .label {
        color: #C3C3C5;
        font-size: 22rpx;
        line-height: 1.5;

      }

      .uploadBoxs {
        margin-right: 30rpx;
        overflow: hidden;

        ::v-deep .u-upload__button {
          margin: 20rpx 0 0;
        }

        ::v-deep .u-upload__button__text {
          color: #7694B0;
          font-size: 30rpx;
          line-height: 1.5;

        }
      }

    }
  }
</style>
